import * as pako from 'pako'

let blockApi = {} as any

import { get, post } from './http/axios'

blockApi.broadcast = async function (hex, options) {
	console.log('broadcast', options)
	if (options.blockChain.toUpperCase() === 'MVC') {
		const mvcServerBase = `https://${options.chainNetwork}.mvcapi.com`
		return await post(`${mvcServerBase}/tx/broadcast`, {
			hex
		}, undefined)
	} else if (options.blockChain.toUpperCase() === 'BSV') {
		const config = {
			headers: {
				'Content-Type': 'application/json'
			}
		}
		const network = options.chainNetwork === 'mainnet' ? 'main' : 'test'
		const bsvServerBase = `https://api.whatsonchain.com/v1/bsv/${network}`
		const res = await post(
			`${bsvServerBase}/tx/raw`,
			{
				txhex: hex
			},
			config
		)
		return {
			txid: res,
			message: res ? '' : 'Broadcast error'
		}
	}

	throw new Error('not support')
}

blockApi.broadcastGzip = async function (hex, options) {
	//console.log('broadcast', options)
	let baseURL: any = null
	if (options.blockChain === 'MVC') {
		baseURL = `https://${options.chainNetwork}.mvcapi.com`
	}
	// console.log(JSON.stringify(payloadList))
	// Compress the payload using gzip
	const compressedPayload = pako.gzip(JSON.stringify(hex)).toString()

	// Send the compressed payload using fetch
	const response:any = await post(
		`${baseURL}/tx/broadcast`,
		{
			hex: compressedPayload
		},
		{
			headers: {
				'Content-Encoding': 'gzip',
				'Content-Type': 'application/json'
			}
		}
	)

	// Handle the response
	if (response.ok) {
		//console.log(await response.json())
		console.log('Transaction broadcasted successfully')
		//return await response.json()
	} else {
		console.error(`Error: ${response.status} - ${response.statusText}`)
	}
	return response
}

blockApi.broadcastBatchGzip = async function (payloadList, options) {
	let baseURL:any = null
	if (options.blockChain === 'MVC') {
		baseURL = `https://${options.chainNetwork}.mvcapi.com`
	}

	// console.log(JSON.stringify(payloadList))
	// Compress the payload using gzip
	const compressedPayload = pako.gzip(JSON.stringify(payloadList))

	// Send the compressed payload using fetch
	const response = await fetch(`${baseURL}/tx/broadcast/batch`, {
		method: 'POST',
		body: compressedPayload,
		headers: {
			'Content-Encoding': 'gzip',
			'Content-Type': 'application/json'
		}
	})

	// Handle the response
	if (response.ok) {
		//console.log(await response.json())
		console.log('Transaction broadcasted successfully')
		//return await response.json()
	} else {
		console.error(`Error: ${response.status} - ${response.statusText}`)
	}
	return response
}

blockApi.getAddressUtxo = async function (address, options) {
	if (options.blockChain === 'MVC') {
		const mvcServerBase: any = `https://${options.chainNetwork}.mvcapi.com`
		return await get(`${mvcServerBase}/address/${address}/utxo`, undefined, undefined)
	} else if (options.blockChain.toUpperCase() === 'BSV') {
		const network = options.chainNetwork === 'mainnet' ? 'main' : 'test'
		const bsvServerBase = `https://api.whatsonchain.com/v1/bsv/${network}`
		const __utxos:any = await get(`${bsvServerBase}/address/${address}/unspent`, undefined, undefined)
		__utxos.map((utxo) => {
			utxo.address = address
			utxo.txid = utxo.tx_hash
			utxo.outIndex = utxo.tx_pos
			return utxo
		})
		return __utxos
	}
	throw new Error('not support')
}

blockApi.getAddressBalance = async function (address, options) {
	if (options.blockChain === 'MVC') {
		const mvcServerBase = `https://${options.chainNetwork}.mvcapi.com`
		return await get(`${mvcServerBase}/address/${address}/balance`, undefined, undefined)
	} else if (options.blockChain.toUpperCase() === 'BSV') {
		const network = options.chainNetwork === 'mainnet' ? 'main' : 'test'
		const bsvServerBase = `https://api.whatsonchain.com/v1/bsv/${network}`
		return await get(`${bsvServerBase}/address/${address}/balance`, undefined, undefined)
	}

	throw new Error('not support')
}

export default blockApi
